<?php
namespace yakexi;
define('BASEPATH', $_SERVER['DOCUMENT_ROOT'] . '/');
require 'Request.php';
require 'Response.php';
require 'RequestHandler.php';
require 'Template.php';

final class Yakexi
{
	private $debug;
	private $url_mapping;
	private $request;
	private $response;
	
	public function __construct($url_mapping, $debug=False)
	{
		$this->debug = $debug;
		sae_set_display_errors($debug);
		if ($debug)
			error_reporting(E_ALL & ~E_STRICT);
		else
			error_reporting(0);

		$this->url_mapping = $url_mapping;

		$this->request = new Request;
		$this->response = new Response;

		$this->current_request_args = array();
	}

	public function run_sae_app()
	{
		$path = $this->request->path;
		foreach ($this->url_mapping as $regexp => $handler_class)
		{
			if (substr($regexp, 0, 1) !== '^')
				$regexp = '^'.$regexp;
			if (substr($regexp, -1) !== '$')
				$regexp .= '$';

			// Does the RegEx match?
			$matches = array();
			if (preg_match('#'.$regexp.'#', $path, $matches))
			{
				try
				{
					$handler = new $handler_class;
					$handler->initialize($this->request, $this->response);
					$method = $handler->request->method;
					if (count($matches) > 1)
					{
						array_shift($matches);
						call_user_func_array(array($handler, $method), $matches);
					}
					else
					{
						$handler->$method();
					}
				}
				catch(Exception $e)
				{
					$this->response->set_status(500);
					$this->response->write('Something was wrong');
				}

				return;
			}
		}
		$this->response->set_status(404);
		$this->response->write('Not Found');
	}
}
